import { Button, Checkbox, Form, Input, message, Modal, Select } from 'antd';
import { regExp, rules } from '../../../constants/constants';
import { UploadImg } from '../../components/UploadImg';
import { MultipleChoiceInput } from '../../components/multiple-choice-input';
import { request } from '../../../utils/request';
import { useNavigate } from 'react-router-dom';
import { routes } from '../../../routes';
import { useEffect, useRef, useState } from 'react';
import SkuList from '../../components/sku-list';
import { v4 as uuidv4 } from 'uuid';

const FormItem = Form.Item;
const CheckBoxGroup = Checkbox.Group;
const ProductAdd = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [categoryList, setCategoryList] = useState([]);
  const [selectedCategory, setSelectedCategory] = useState(null);
  const [allCategoryList, setAllCategoryList] = useState([]);
  const [modalVisible, setModalVisible] = useState(false);
  const skuListDataRef = useRef([]);

  useEffect(() => {
    getCategoryList();
  }, []);

  const getCategoryList = async () => {
    const data = await request('/admin/product/category/list', {
      method: 'GET',
      data: {
        pageNo: 0,
        pageSize: 100000
      }
    });
    setAllCategoryList(data.list);
    setCategoryList(data.list.map(item => {
      return {
        label: item.name,
        value: item.categoryId
      };
    }));
  };

  const onFinish = async (values) => {
    const skuListData = skuListDataRef.current;
    const checkResult = checkSku(skuListData, values);
    if (!checkResult.status) {
      message.error(checkResult.desc);
      return;
    }
    let params: any = {};
    params.name = values.name;
    params.productCode = values.productCode;
    params.basePrice = values.basePrice;
    params.totalStock = values.totalStock;
    params.categoryId = values.categoryId;
    params.productOverview = values.productOverview;

    if (values && values.config) {
      let base = values.config.map((item => {
        return {
          [item]: true
        };
      }));
      let config = Object.assign({}, ...base);
      params = { ...params, ...config };
    }
    if (values && values.productChoice) {
      params.productChoice = values.productChoice;
    }
    if (values && values.imageList) {
      params.imageList = values.imageList.map((item) => {
        return item.url;
      });
    }
    const res = await request('/admin/product/add', {
      method: 'POST',
      pureData: false,
      data: params
    });
    if (res.code === '1') {
      await addSku(skuListData, res.data.productId);
      return;
    }
    message.error(res.desc);
  };

  const checkSku = (skuList, product) => {
    if (skuList.length === 0) {
      return {
        status: false,
        desc: '请填写产品规格'
      };
    }
    const totalStock = skuList.reduce((prev, next) => {
      return prev + Number(next.stock);
    }, 0);
    if (isNaN(totalStock)) {
      return {
        status: false,
        desc: '请填写正确的库存'
      };
    }
    if (totalStock !== Number(product.totalStock)) {
      return {
        status: false,
        desc: '产品库存与规格库存不一致'
      };
    }
    return {
      status: true
    };
  };

  const addSku = async (skuListData, productId) => {
    //删除除skuListData中的id
    skuListData = skuListData.map((item) => {
      return {
        price: item.price,
        stock: item.stock,
        specs: item.specs
      };
    });
    const res = await request('/admin/product/sku/add', {
      method: 'POST',
      pureData: false,
      data: {
        productId: productId,
        skuList: skuListData
      }
    });
    if (res.code === '1') {
      message.success('添加成功');
      navigate(routes.ADMIN_PRODUCT_LIST);
      return;
    }
    message.error(res.desc);
  };


  return (
    <div style={{ marginLeft: '300px', maxHeight: '100%' }}>
      <Modal
        title={'填写产品规格'}
        width={1000}
        open={modalVisible}
        onOk={() => {
          setModalVisible(false);
        }}
        onCancel={() => setModalVisible(false)}
      >
        <SkuList skuList={selectedCategory?.optionalConfig?.concat([{
          name: 'price', value: '', id: uuidv4()
        }, {
          name: 'stock', value: '', id: uuidv4()
        }])} onChange={(e) => {
          skuListDataRef.current = e;
        }} />
      </Modal>
      <h1>添加产品</h1>
      <Form
        form={form}
        onFinish={onFinish}
        layout="horizontal"
      >
        <FormItem
          name={'imageList'}
          label={'产品图片'}
          required={true}
          rules={[{
            validator: (rule, value) => {
              if (!value || value.length === 0) {
                return Promise.reject('请上传产品图片');
              }
              return Promise.resolve();
            }
          }]}
        >
          <UploadImg  onChange={(e)=>{}}/>
        </FormItem>

        <FormItem
          name={'name'}
          label={'产品名称'}
          rules={[{ required: true, message: rules.PRODUCT_NAME }]}
        >
          <Input style={{ width: '200px' }} />
        </FormItem>

        <FormItem
          name={'productCode'}
          label={'产品编码'}
          rules={[{ max: 12, message: '产品编码最多12个字符' }]}
        >
          <Input style={{ width: '200px' }} />
        </FormItem>

        <FormItem
          name={'categoryId'}
          label={'产品分类'}
          rules={[{ required: true, message: '请选择产品分类' }]}
        >
          <Select onSelect={(val) => {
            allCategoryList.forEach((item) => {
              if (item.categoryId === val) {
                setSelectedCategory(item);
              }
            });
          }} options={categoryList} style={{ width: '200px' }} />
        </FormItem>

        <FormItem
          name={'productOverview'}
          label={'产品概述'}
          rules={[{
            required: true, message: rules.PRODUCT_OVERVIEW
          }, {
            max: 50,
            message: '产品概述最多50个字符'
          }]}
        >
          <Input.TextArea style={{ width: '400px' }} />
        </FormItem>

        <FormItem
          name={'basePrice'}
          label={'产品价格'}
          rules={[{ required: true, message: rules.PRODUCT_PRICE }, {
            pattern: regExp.PRODUCT_PRICE,
            message: '请输入正确的价格'
          }]}
        >
          <Input style={{ width: '200px' }} />
        </FormItem>
        <FormItem
          name={'totalStock'}
          label={'产品库存'}
          rules={[{ required: true, message: rules.PRODUCT_STOCK }, {
            max: 8,
            message: '产品库存最多8位数'
          }, {
            pattern: regExp.PRODUCT_STOCK,
            message: '请输入正整数'
          }]}
        >
          <Input style={{ width: '200px' }} />
        </FormItem>
        <FormItem
          name={'config'}
          label={'产品配置'}
        >
          <CheckBoxGroup
            options={[
              {
                label: '7天无理由退货',
                value: 'returnGroud7'
              }, {
                label: '提供上门服务',
                value: 'provideHome'
              }, {
                label: '自提',
                value: 'persionPickUp'
              }, {
                label: '破损包退换',
                value: 'damagedPackageReturn'
              }, {
                label: '闪电退款',
                value: 'lightningRefund'
              }, {
                label: '全球发货',
                value: 'provideGlobal'
              }
            ]}
          />
        </FormItem>

        <FormItem
          name={'productChoice'}
          label={'不可选产品参数详情'}
        >
          <MultipleChoiceInput onChange={(e) => {
            console.log(e);
          }} />
        </FormItem>

        {
          selectedCategory &&
          <FormItem
            name={'skuList'}
            label={'产品规格'}
          >
            <Button onClick={() => setModalVisible(true)} type={'default'}>
              添加产品规格
            </Button>
          </FormItem>
        }

        <FormItem>
          <Button type={'primary'} style={{ width: '350px', marginLeft: '100px' }} htmlType={'submit'}>
            添加商品
          </Button>
        </FormItem>
      </Form>
    </div>
  );
};

export default ProductAdd;